/*******************************************************************************
 * Filename: team.js 
 *
 * This file contains common JavaScript funciton used throughout
 * the Fantasy Broomball website.  Many of the common functions 
 * are used to support frequent AJAX requests.
 *
 * Author: Phil Peterson
 * Date: 09/13/2009
 *
 ******************************************************************************/

//============================================================================
// Global variables used

var g_players         = {};
var g_game_data       = {};
var g_over_bench      = false;
var g_bench_player_id = "";
var g_swapped_names   = false;
var g_display_week    = 0;
//============================================================================

/**
 * @Desc This function is called when the onload listener for the body
 *       of the page detects that the page has been successfully loaded.
 *       It is a wrapper function which simply calls other functions 
 *       needed to be called onload.
 *
 **/
function postLoad(){
	var tabberArgs = {};
	g_display_week = g_cur_week;
	setWeekButtons();
	collapseRows();
	setRows();
	getPlayerPosition();
}


function setRows(){

    var table = document.getElementById("trade_table");
    var rows  = table.rows;
    var alter = true;
    
    for (var i = 1; rows[i].id != "previous"; i++){
        if (alter){
            rows[i].className = "shade_odd";
            rows[i].style.backgroundColor = "#E0F0F9";
        }
        else {
            rows[i].className = "shade_even";
            rows[i].style.backgroundColor = "#FFFFFF";
        }
        alter = !alter;
   }
}


/**
 * @Desc Function used to set the back and forward arrows for
 *       the scoreboard.
 *
 **/
function setWeekButtons(){

	if (g_display_week != 1)
		//Set the visibility of the back button
		document.getElementById("left_arrow").style.visibility = "visible";
	else
		document.getElementById("left_arrow").style.visibility = "hidden";
}


/**
 *
 * @Desc This function is called anytime there is a click on the body of the page.
 *       The function proceeds to loop through all of the home players.  The 
 *       function first checks if the previous click was over a player on the
 *       bench.  If so, it checks to see if the current click is over a player
 *       on the ice.  The function then proceeds to call another function to 
 *       swap the two players.
 *
 * @param e The onclick event detected on the screen
 *
 **/
function checkPosition(e){

	var the_event = e || window.event;

	//Get the x and y coordinates from the click
	var x_click = parseInt(the_event.pageX,10);
	var y_click = parseInt(the_event.pageY,10);
	
	//Loop through all of the home players
	for (var id in g_players){

		//Check if the overBench flag is already set, meaning that the laststyle
		//  click was for a player on the bench.  Need to check if the current
		//  click is on a player on the ice.
		//Check if the onclick event occured over a player on the bench	
		if (g_over_bench == true &&
			g_players[id].type == "ice" &&
			x_click >= g_players[id].x_lower && 
		    x_click <= g_players[id].x_upper && 
			y_click >= g_players[id].y_lower && 
			y_click <= g_players[id].y_upper){

			swapPlayers(g_bench_player_id,id);
			deselectPlayers();
			return;
		}

		else if (g_players[id].type == "bench" &&
			x_click >= g_players[id].x_lower && 
		    x_click <= g_players[id].x_upper && 
			y_click >= g_players[id].y_lower && 
			y_click <= g_players[id].y_upper){
	
			//Set the overBench flag because this click was over the bench
			g_over_bench = true;
			//Set variable to know which player was clicked
			g_bench_player_id = id;
			//Set the players on the ice to trans_team_id + "," + (g_cur_weekparent
			highlightPlayers(document.getElementById(id));
			return;
		}
	}

	//The click was not on a player on the bench.  Need to reset all of the 
	//images to be not transparent
	g_over_bench = false;
	deselectPlayers();

}

/**
 * @Desc This function takes the id of the bench and ice players which the user chose
 *       to swap.
 *
 * @param bench_player_id the id from the players object array  of the bench player to swap
 * @param ice_player_id the id from the players object array of the ice player to swap
 *
 **/
function swapPlayers(bench_player_id, ice_player_id){

	//Swap the players names
	var temp = g_players[bench_player_id].name;
	g_players[bench_player_id].name = g_players[ice_player_id].name;
	g_players[ice_player_id].name = temp;

	//Change the labels to show the swap
	var temp_arr = g_players[bench_player_id].name.split(" ");
	var bench_label = document.getElementById(bench_player_id + "_label");
	bench_label.innerHTML = temp_arr[0][0] + ". " + temp_arr[1];
	bench_label.style.color = "#000000";
	bench_label.style.backgroundColor = "#E2AFAF";
	
	//Change the labels to show the swap
	temp_arr = g_players[ice_player_id].name.split(" ");	
	var ice_label = document.getElementById(ice_player_id + "_label");
	ice_label.innerHTML = temp_arr[0][0] + ". " + temp_arr[1];
	ice_label.style.color = "#000000";
	ice_label.style.backgroundColor = "#E2AFAF";

	g_over_bench = false;
	g_swapped_names = false;
	g_bench_player_id = "";

    //Perform an HTTP request to store this player swap from bench
    //to ice, so that this roster update will be saved the next time 
    //the team home page is viewed
	var type        = "rosterUpdate";
	var param_names = "type,teamId,benchId,iceId";
	var param_vals  =  type + "," + g_team_id + "," + g_players[bench_player_id].db_id + "," + g_players[ice_player_id].db_id;
	var url         = "request_data.php";

	postRequest(param_names, param_vals, url);

	//Need to swap the database ids for the players as well
	temp = g_players[bench_player_id].db_id;
	g_players[bench_player_id].db_id = g_players[ice_player_id].db_id;
	g_players[ice_player_id].db_id = temp;
}

/**
 * @Desc Function to swap the labels of the player being hovered over on the ice.
 *       Labels won't be swapped if a bench player hasn't been selected.
 *
 * @param bench_label the HTML label of the bench player selected
 * @param ice_label the HTML label of the bench player hovered over
 *
 **/
function swapNames(bench_label, ice_label){

	//Change the font and background colors accordingly
	if (g_swapped_names){
		ice_label.style.color = "#FFFFFF";
		ice_label.style.backgroundColor = "#000000";
	
		bench_label.style.color = "#FFFFFF";
		bench_label.style.backgroundColor = "#000000";
	}
	else{
		ice_label.style.color = "#000000";
		ice_label.style.backgroundColor = "#E2AFAF";
	
		bench_label.style.color = "#000000";
		bench_label.style.backgroundColor = "#E2AFAF";
	}

	//Swap the names
	var bench_name = bench_label.innerHTML;
	var ice_name   = ice_label.innerHTML;

	ice_label.innerHTML = bench_name;
	bench_label.innerHTML = ice_name;
}


/**
 * @Desc Function posts the last games score and opponent on the scoreboard.  This
 *       function is called when the back arrow is clicked on the scoreboard.
 *
 **/
function getLastGame(){

	//Check if previous week exists
	if (g_display_week > 1){
		//Decrement the current display week
		g_display_week = g_display_week - 1;
		//Update the display week under the scoreboard
		document.getElementById('week_shown').innerHTML = g_display_week;
		//Activate next week buttton
		document.getElementById("right_arrow").style.visibility = "visible";
		//Perform an HTTP request to get the previous weeks data
		var param_names = "type,teamId,curWeek";
		var param_vals  = "weekData," + g_team_id + "," + g_display_week;
		var url         = "request_data.php";

		var response = postRequest(param_names, param_vals, url);
		
		if (response != 'bye'){
		    //The response is in the form team1id,team1name,team1score|team2id,team2name,team2score
		    var tempArr = response.split("|");
		    var team_1_data = tempArr[0].split(",");
		    var team_2_data = tempArr[1].split(",");

		    if (g_team_id == team_1_data[0]){
			    var home_team  = team_1_data[1];
			    var home_score = team_1_data[2];
			    var away_team  = team_2_data[1];
			    var away_score = team_2_data[2];
		    }
		    else {
			    var home_team  = team_2_data[1];
			    var home_score = team_2_data[2];
			    var away_team  = team_1_data[1];
			    var away_score = team_1_data[2];
		    }

		    displayScore(home_score,'home');
		    displayScore(away_score,'away');
		
		    displayTeamNames(home_team, away_team);
        }
        else {
    	    displayTeamNames(g_team_name, "Bye Week");
    	    setScoreboard("hidden");
    	}
	}
	
	if (g_display_week == 1)
		document.getElementById("left_arrow").style.visibility = "hidden";

}


/**
 * @Desc Function posts the last games score and opponent on the scoreboard.  This
 *       function is called when the back arrow is clicked on the scoreboard.
 *
 **/
function getNextGame(){

	//Check if previous week exists
	if (g_display_week < g_cur_week){
		//Decrement the current display week
		g_display_week = g_display_week + 1;
		document.getElementById("left_arrow").style.visibility = "visible";
		//Update the display week under the scoreboard
		document.getElementById('week_shown').innerHTML = g_display_week;
		//Perform an HTTP request to get the previous weeks data
		var param_names = "type,teamId,curWeek";
		var param_vals  = "weekData," + g_team_id + "," + g_display_week;
		var url         = "request_data.php";

		var response = postRequest(param_names, param_vals, url);
				
		if (response != 'bye'){
    		//The response is in the form team1id,team1name,team1score|team2id,team2name,team2score
    		var tempArr = response.split("|");
    		var team_1_data = tempArr[0].split(",");
    		var team_2_data = tempArr[1].split(",");

    		if (g_team_id == team_1_data[0]){
    			var home_team  = team_1_data[1];
			    var home_score = team_1_data[2];
			    var away_team  = team_2_data[1];
			    var away_score = team_2_data[2];
		    }
		    else {
			    var home_team  = team_2_data[1];
			    var home_score = team_2_data[2];
			    var away_team  = team_1_data[1];
			    var away_score = team_1_data[2];
		    }

		    displayScore(home_score,'home');
		    displayScore(away_score,'away');

		    displayTeamNames(home_team, away_team);
	    }
	    else {
    	    displayTeamNames(g_team_name, "Bye Week");
    	    setScoreboard("hidden");
    	}
    }

	if (g_display_week == g_cur_week){
		document.getElementById("right_arrow").style.visibility = "hidden";
		//Set the scoreboard numbers to hidden because no score has been recorded
		setScoreboard("hidden");
	}
}

function displayTeamNames(home_team, away_team){
	document.getElementById("home_team_name").innerHTML = home_team;
	document.getElementById("away_team_name").innerHTML = away_team;
}

function setScoreboard(vis){
	var setVis = document.getElementsByClassName('digit');
	for (var i = 0; i < setVis.length; i++)
		setVis[i].style.visibility = vis;
}


function displayScore(score, team){

	var temp_score = score;
	var digit = temp_score % 10;
	var image_url = "url(images/rink/" + digit + ".gif)";
	document.getElementById(team+'_1_digit').style.backgroundImage = image_url;
	temp_score = parseInt(temp_score / 10,10);

	digit = temp_score % 10;
	image_url = "url(images/rink/" + digit + ".gif)";
	document.getElementById(team+'_2_digit').style.backgroundImage = image_url;
	temp_score = parseInt(temp_score / 10,10);

	digit = temp_score % 10;
	image_url = "url(images/rink/" + digit + ".gif)";
	document.getElementById(team+'_3_digit').style.backgroundImage = image_url;

	setScoreboard("visible");
}
/**
 * @Desc Function to swap the transparent and non-transparent images
 *       of the ice player being hovered
 *
 * @param elem the HTML player element which was caused the onmousehover event
 *
 **/
function hoverIcePlayer(elem){

	if (g_over_bench){

		//Set the flag that the names should be swapper
		g_swapped_names = true;
		//Swap the image to make it non-transparent
		elem.src = "images/rink/red_player.png";
		//
		swapNames(document.getElementById(g_bench_player_id + "_label"), document.getElementById(elem.id + "_label"));
	}
}

/**
 * @Desc Function to swap the transparent and non-transparent images of
 *       the ice player being hovered
 *
 * @param elem the HTML player element which was caused the onmouseout event
 *
 **/
function unhoverIcePlayers(elem){

	//Need to swap the names back because the user is no longer hovering
	if (g_over_bench && g_swapped_names){
		//
		elem.src = "images/rink/redplayerhover.png";
		//
		g_swapped_names = false;
		//
		swapNames(document.getElementById(g_bench_player_id + "_label"), document.getElementById(elem.id + "_label"));

	}

}

/**
 * @Desc Function to swap non-transparent player image with the
 *       transparent version
 *
 * @param elem the HTML bench player element that was clicked
 *
 **/
function highlightPlayers(elem){

	//Highlight the player selected
	elem.src = "images/rink/red_player.png";

	//Loop through and make the rest of the players transparent
	for (var id in g_players){
		if (id != elem.id)
			document.getElementById(id).src = "images/rink/redplayerhover.png";
	}
}

/**
 * @Desc Function deselects all of the players on the ice, aka. swaps
 *       their images from transparent to non-transparent.
 *
 **/
function deselectPlayers(){
		
	//Set all of the players to the non-transparent image
	for (var id in g_players){
		document.getElementById(id).src = "images/rink/red_player.png";
	}
}

/**
 * @Desc This function populates the players object with information needed for
 *       implementing the drag and drop feature.  Each player object has the following
 *       properties
 * 
 **/
function getPlayerPosition(){

	var ice_ids = [];
	var bench_ids = [];
	var cur_left = 0;
	var cur_top  = 0;
	var x_offset = 0;
	var y_offset = 0;
	//var y_screen_offset = 170;
	var y_screen_offset = 0;
	var obj;

	if (navigator.appVersion.indexOf("Win") != -1){
		//y_screen_offset = 120;
		y_screen_offset = 0;
	}

	//Loop through and get the array of ice ids populated
	for (var i = 1; i < 7; i++)
		ice_ids[i-1] = "home_player_" + i;

	//Loop through and get the array of bench ids populated
	for (i = 1; i < 5; i++)
		bench_ids[i-1] = "home_bench_" + i;

	//Loop through to setup information for players on the ice
	for (i = 0; i < ice_ids.length; i++){
		obj = document.getElementById(ice_ids[i]);
		x_offset = obj.offsetWidth;
		y_offset = obj.offsetHeight;
		cur_left = 0;
		cur_top  = 0;

		//Check if this object has a parent
		if (obj.offsetParent){
			do {
				//Increment the location variables
				cur_left += obj.offsetLeft;
				cur_top  += obj.offsetTop;
			} while (obj = obj.offsetParent);
		}

		//Store the information for this player
		g_players[ice_ids[i]] = {
			x_lower : cur_left,
			x_upper : cur_left + x_offset,
			y_lower : cur_top + y_screen_offset,
			y_upper : cur_top + y_offset + y_screen_offset,
			type   : "ice",
			name   : document.getElementById(ice_ids[i]).alt,
			db_id  : document.getElementById(ice_ids[i]).name
		};
	}
	//Loop through to setup information for players on the bench
	for (i = 0; i < bench_ids.length; i++){
		obj = document.getElementById(bench_ids[i]);
		x_offset = parseInt(obj.offsetWidth,10);
		y_offset = parseInt(obj.offsetHeight,10);
		cur_left = 0;
		cur_top  = 0;

		//Check if this object has a parent
		if (obj.offsetParent){
			do {
				cur_left += obj.offsetLeft;
				cur_top  += obj.offsetTop;
			} while (obj = obj.offsetParent);
		}
		
		//Store the information for this player
		g_players[bench_ids[i]] = {
			x_lower : cur_left,
			x_upper : cur_left + x_offset,
			y_lower : cur_top + y_screen_offset,
			y_upper : cur_top + y_offset + y_screen_offset,
			type   : "bench",
			name   : document.getElementById(bench_ids[i]).alt,
			db_id  : document.getElementById(bench_ids[i]).name
		};
	}
}


/**
* @Desc Cycles through Tables with the class 'expandable' and hides
*     	all children rows under parent rows.
*
**/
function collapseRows(){
	var tbl;
	tables = document.getElementsByTagName('table');

	// Cycle through the tables on the page
	for (i = 0; i < tables.length; i++){
	
		// If the table is expandable, select it, otherwise
		// skip this iteration
		if (tables[i].className.indexOf('expandable') != -1){
			tbl = tables[i];
		} 
        else {
			continue;
		}

		if (typeof tbl=='undefined'){
			alert('Could not find a table of expandable class!');
			return;
		}

		var len = tbl.rows.length;	
		var link = '<a href="#" onclick="toggleSection(this); return false;">+</a>';
		var row_head = tbl.rows[0].cells[0].innerHTML;

		// Cycle through the rows
		for (j = 0; j < len; j++){
			var m = tbl.rows[j].cells[0].innerHTML;;

			// If it is a parent row, give it the expand link.
			if (m == '+' || j == 0){
				row_head = m;
				if (j != 0)
				{
					tbl.rows[j].cells[0].innerHTML = link;
					tbl.rows[j].setAttribute('onclick','toggleSection(this); return false;');
					tbl.rows[j].cells[0].style.visibility = "hidden";
				}
			}
			else{
				// The row is a child row, so hide it.
				tbl.rows[j].style.display = 'none';
			}
		}
	}
}

/**
* @Desc Returns the parent of the provided HTML element
*
* @param el - the element to get the parent of
* @param pTagName - the expected HTML tag name of the parent
*
* @return the parent element
*
**/
function getParent(el, pTagName){
	if (el == null) {
		return null;
	}
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase()){
		return el;
	}
	else{
		return getParent(el.parentNode, pTagName);
	}
}

/**
* @Desc If the toggle link is clicked, toggle the visibility of the children rows
*       of the parent.
*
* @param lnk - the link object clicked on
*
**/
function toggleSection(td) {
	var table = getParent(td, 'table');
	var len = table.rows.length;
	var tr = getParent(td, 'tr');
	var row_index = tr.rowIndex;
	var row_head = table.rows[row_index].cells[0].innerHTML;
	var lnk = table.rows[row_index].cells[0];

	lnk.innerHTML = (lnk.innerHTML == '+')?'-':'+';
	var v_style = (table.rows[row_index+1].style.display=='none')?'':'none';

	var flag = 0;
	var i = row_index+1;

	while (flag == 0 && table.rows[i] != null){
		if (table.rows[i].cells[0].innerHTML != ''){
			flag = 1;
		}
		else{
			table.rows[i].style.display = v_style;
		}
		i = i + 1;
	}
}


/**
*
*
*
*
**/
function rowHover(elem){
    elem.style.backgroundColor = "#F5BE1B";
    elem.style.background = "#F5BE1B url(images/right_arrow.png) 5px 3px no-repeat";
    elem.style.cursor = "pointer";
}


/**
*
*
*
*
**/
function rowUnHover(elem){
    if (elem.className == "shade_odd")
        elem.style.backgroundColor = "#E0F0F9";  
    else
        elem.style.backgroundColor = "#FFFFFF";
    //elem.cursor = "pointer";
    elem.style.backgroundImage = "";
}


/**
*
*
*
**/
function acceptTrade(elem){

    var response = confirm("Are you sure you want to accept this trade");
    if (!response)
        return;
    
    //The team owner would like to accept the trade
   	var temp        = elem.id.split("_");
   	var trade_id    = temp[1];    
	var type        = "acceptTrade";
	var param_names = "type,tradeId";
	var param_vals  = type + "," + trade_id;
	var url         = "request_data.php";

	response = postRequest(param_names, param_vals, url);
	
	alert(response);
	
	window.location.reload();
}

function declineTrade(elem){

    var response = confirm("Are you sure you want to decline this trade");
    if (!response)
        return;
    
    //The team owner would like to decline the trade
   	var temp        = elem.id.split("_");
   	var trade_id    = temp[1];    
	var type        = "declineTrade";
	var param_names = "type,tradeId";
	var param_vals  = type + "," + trade_id;
	var url         = "request_data.php";

	response = postRequest(param_names, param_vals, url);
	
	alert(response);
	
	window.location.reload();

}
